<?php

require __DIR__ . '/../vendor/autoload.php';

$app = require_once __DIR__ . '/../bootstrap/app.php';

$app->make(\App\Console\Kernel::class)->bootstrap();

/* ============== Write Codes Below ================= */

//查询剩余库存为0且状态为在售的转售商品
$products = \App\Models\Product::query()
    ->where('status', \App\Enums\ProductStatus::ON_SALE)
    ->where('type', \App\Enums\ProductType::RESALE)
    ->where('left_count', 0)
    ->get();

foreach ($products as $product) {
    //查询商品是否有支付成功的订单
    $paidOrderCount = \App\Models\Order::query()
        ->where('product_id', $product->id)
        ->where('is_resale', true)
        ->where('order_status', \App\Enums\OrderStatus::PAID)
        ->count();

    if ($paidOrderCount > 0) {
        $product->status = \App\Enums\ProductStatus::STOP;
        $product->save();
    }

    echo sprintf('商品ID: %s, 已支付订单数量:%s, 商品状态改为:%s', $product->id, $paidOrderCount, $product->status) . PHP_EOL;
}
